package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.modules.base.dbEntity.RUserInfoSysRoleEntity;
import com.ych.modules.base.mapper.RUserInfoSysRoleMapper;
import com.ych.modules.base.service.IRUserInfoSysRoleService;
import com.ych.modules.sql.service.ISysSqlService;
import com.ych.modules.sql.util.SqlBaseUtil;
import com.ych.utils.MapUtils;
import com.ych.utils.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/5
 * Time: 16:08
 * Description:
 */
@Service("IRUserInfoSysRoleService")
public class RUserInfoSysRoleServiceImpl extends ServiceImpl<RUserInfoSysRoleMapper, RUserInfoSysRoleEntity> implements IRUserInfoSysRoleService {
    @Autowired
    private ISysSqlService iSysSqlService;

    @Override
    public List<String> queryRoleIdList(String userId) {
        String sql = "select role_id AS var1 from r_user_info_sys_role where user_id = '" + userId + "'";
        List<Map<String, Object>> listMap = iSysSqlService.selectSql(sql);
        return SqlBaseUtil.SqlReturnListObj(listMap, null);
    }

    @Override
    public void saveOrUpdate(String userId, List<String> roleIdList) {
        //先删除用户与角色关系
        this.deleteByMap(new MapUtils().put("user_id", userId));
        if (roleIdList == null || roleIdList.size() == 0) {
            return;
        }
        //保存用户与角色关系
        List<RUserInfoSysRoleEntity> list = new ArrayList<>(roleIdList.size());
        for (String roleId : roleIdList) {
            RUserInfoSysRoleEntity tIpmsUserRoleEntity = new RUserInfoSysRoleEntity();
            tIpmsUserRoleEntity.setId(UUID.randomUUID());
            tIpmsUserRoleEntity.setUserId(userId);
            tIpmsUserRoleEntity.setRoleId(roleId);

            list.add(tIpmsUserRoleEntity);
        }
        this.insertBatch(list);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteBatch(String[] roleIds) {
        for (String roleId : roleIds) {
            super.baseMapper.deleteByMap(new MapUtils().put("role_id", roleId));
        }
    }
}
